<?php
namespace Api\Controller;
use Api\Controller\CommonController;
class PayController extends CommonController {
	public function _initialize(){
		parent::_initialize();
		 
		//登录验证
		$this->_checkLogin();
	}
	
	/**
	 *  商品预下单接口 
	 */
	/* public function orderCouponPre(){
		$data=array(
			"couponCode"=>I("couponCode"),
			"quantity"=>intval(I("quantity"))
		);
		
		$result=$this->_orderCouponPre($data['couponCode'], $data['quantity'], "18575020603");
		//dump($result);
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		$this->_returnJson(array("result"=>1,"couponName"=>$result['couponName'],"orderSn"=>$result['orderSn']));
	} */
	
	/**
	 *  商品下单确认
	 */
	/* public function confirmCouponOrder(){
		$data=array(
				"orderSn"=>I("orderSn"),
		);
		if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		$result=$this->_confirmCouponOrder($data['orderSn'],"18575020603");
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>$this->apiErrorMsg,"code"=>"119") );
		dump($result);
		$this->_returnJson(array("result"=>1));
	} */
	
	
	/**
	 *  生成支付接口url地址 
	 */
	public function getPayUrl(){
		$data=array(
			"orderSn"=>I("orderSn"),
		);
		if(!isNotEmptyArr($data)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		//查询订单是否存在
		$order=D("Order")->getOrder("",array("orderSn"=>$data['orderSn'],"isOn"=>1,"userID"=>$this->user['uid']));
		if(!$order) $this->_returnJson(array("result"=>0,"info"=>"order is not exist","code"=>"133"));
		if($order['status'] !=0) $this->_returnJson(array("result"=>0,"info"=>"order had pay","code"=>"134"));
		
		//查询订单是否超出限购数量
		$orderGoods=M('OrderGoods')->where(array('orderSn'=>$data['orderSn']))->select();
		foreach ($orderGoods as $a){
    		$isGoods=D("Goods")->getGoods($a['goodsID'],array("isOn"=>1));
			//限购
			if($isGoods['limitNum'] >= 0){
			    $goodsLogNum=D('OrderGoods')->field('sum(num) as num')->where(array('userID'=>$this->user['uid'],"status"=>1,"goodsID"=>$a['goodsID'],'isOn'=>1))->find();
			    if(($goodsLogNum['num'] +$a['num']) > $isGoods['limitNum']){
			    	$this->_returnJson(array("result"=>0,"info"=>"Beyond the purchase quantity","goodsID"=>$a['goodsID'],'orderGoodsNum'=>$goodsLogNum,'limitNum'=>$isGoods['limitNum'],"code"=>"147"));
			    }
			}
			//月限购
			
			if($isGoods['monthLimitNum'] >= 0){
				$start=strtotime(date('Y-m-01 00:00:00'));
				$end = strtotime(date('Y-m-d H:i:s'));
				$goodsLogNum=D('OrderGoods')->field('sum(num) as num')->where(array('userID'=>$this->user['uid'],"status"=>1,"goodsID"=>$a['goodsID'],'isOn'=>1))->where(array('addTime'=>array('between',array($start,$end))))->find();
			    if(($goodsLogNum['num'] +$a['num']) > $isGoods['monthLimitNum']){
			    	$this->_returnJson(array("result"=>0,"info"=>"Beyond the month purchase quantity","goodsID"=>$a['goodsID'],'orderGoodsNum'=>$goodsLogNum,'monthlimitNum'=>$isGoods['monthLimitNum'],"code"=>"148"));
			    }
			}
    	}
		//查询订单是否超时
		if(time()>($order['addTime']+3600))
			$this->_returnJson(array("result"=>0,"info"=>"error order time","code"=>"149"));
		
		$param =array();
		$param = $this->_makeParam($data['orderSn'],$order['payPrice']);
		$url = C("HUITONG_PAYURL");
		$url .=$param. '&signContent='.urlencode($this->_getSignPKCS12($param));
		
		$this->_returnJson(array("result"=>1,"url"=>$url)) ;
	}
	
	/**
	 * 生成支付接口所需要的参数字符串	
	 */
	private function _makeParam($sn,$amount)
	{
		$data = array();
		$param = array();
		//$returnUrl = "http://".$_SERVER['SERVER_NAME']."/nokapay/action.php?act=returnurl";
		//$notifyUrl = "http://".$_SERVER['SERVER_NAME']."/nokapay/action.php?act=notifyurl";
		$returnUrl = "";
		$notifyUrl = getHost()."/Api/Callback/notify";
		$data['version'] = 'v2.0';
		$data['charset'] = 'UTF-8';
		$data['currency'] = 'CNY';
		$data['partnerCode'] = C("HUITONG_PARTNERCODE");
		$data['accountName'] = C("HUITONG_ACCOUNTNAME");
		$data['orderNo'] = $sn;
		$data['orderTime'] = date('YmdHis');
		$data['amount'] = $amount;
		$data['signType'] = 1;
		$data['returnUrl'] = $returnUrl;
		$data['notifyUrl'] = $notifyUrl;
		$data['extend1'] = getHost().'/Home/Index/backBusiness.html';
		$data['extend2'] = '';
		foreach($data as $k=>$v)
		{
			$param[] = "$k=$v";
		}
		$param = join('&',$param);
		//$param = "version=".$data['version']."&"."charset=".$data['charset']."&"."currency=".$data['currency']."&"."partnerCode=".$data['partnerCode']."&"."accountName=".$data['accountName']."&"."orderNo=".$data['orderNo']."&"."orderTime=".$data['orderTime']."&"."amount=".$data['amount']."&"."signType=".$data['signType']."&"."returnUrl=".$data['returnUrl']."&"."notifyUrl=".$data['notifyUrl']."&"."extend1=".$data['extend1']."&"."extend2=".$data['extend2'];
		//log_message('debug',  'makeParam param:'.$param);
		
		return $param;
	}
    
	/**
	 * 生成pkc12签名	支付接口需要使用
	 */
	private function _getSignPKCS12($msg)
	{
		$pfx = './cert/'.C("HUITONG_PFX");
		$pwd = C("HUITONG_PWD");
		return $this->_signByPkcs12($msg,$pfx,$pwd);
	}
	
	/**
	 *使用pkcs12方式进行签名，并进行base64编码
	 */
	private function _signByPkcs12($msg,$pfx,$pwd='')
	{
		$key=array();
		openssl_pkcs12_read(file_get_contents($pfx),$key,$pwd);
		openssl_sign($msg, $sign, $key['pkey']);
		return base64_encode($sign);
	}	
}